<template>
  <div class="pickupAddress">
    <y-table
        ref="table"
        border
        :getDataWay="{
          data: tableData
        }"
        :columns="columns">
      <template slot="button">
        <el-button type="primary" @click="addAddress">添加地址</el-button>
      </template>
      <el-table-column slot="y-oper" labeml="操作" align="center" header-align="center" width="140">
        <template v-slot="scope">
          <div class="table-buttons">
            <el-button type="primary" size="mini" @click="editAddress(scope.row)">编辑</el-button>
            <el-popconfirm
                title="是否确认删除该地址？"
                @confirm="delAddress(scope.row)">
              <el-button slot="reference" type="danger" size="mini">删除</el-button>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </y-table>
    <y-form
        v-model="forms.formModel"
        :visible.sync="forms.showForm"
        :title="forms.formTypeTitle[forms.formsType]"
        width="50%"
        :formAttrs="forms.formAttrs"
        :columns="forms.formColumns"
        @ensure="ensureModel">
      <template slot="province">
        <y-address-selector
            v-model="provinceVal"></y-address-selector>
      </template>
    </y-form>
  </div>
</template>

<script>
export default {
  name: "pickupAddress",
  inject: ['getDict', 'pattern'],
  computed:{
    provinceVal:{
      get(){
        if(!(this.forms.formModel.province && this.forms.formModel.city && this.forms.formModel.region)){
          return '';
        }
        return [this.forms.formModel.province, this.forms.formModel.city, this.forms.formModel.region];
      },
      set(val){
        if(!val || !val.length){
          [this.forms.formModel.province, this.forms.formModel.city, this.forms.formModel.region] = ['','',''];
        }else{
          [this.forms.formModel.province, this.forms.formModel.city, this.forms.formModel.region] = val;
        }
      }
    }
  },
  asyncComputed:{
    async labelOptions(){
      return this.getDict('address_code');
    }
  },
  data(){
    return{
      tableData: [],
      columns: [{
        label: "省/市/区(县)",
        prop: "province",
        formatter(row){
          if(!row.province) return '';
          return [row.province, row.city, row.region].toString();
        }
      },{
        label: "详细地址",
        prop: "detailAddress"
      },{
        label: "邮编",
        prop: "postCode",
        width: '80'
      },
      {
        label: "排序",
        prop: "sort",
        width: '80'
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加地址',
          'EDIT': '编辑地址'
        },
        currentForm: null,
        formModel: {
          id: '',
          province: '',
          city: '',
          region: '',
          detailAddress: '',
          postCode: '',
          sort: ''
        },
        showForm: false,
        formAttrs:{
          labelWidth: '125px',
          rules: {
            province: [{required: true, message: "请选择省/市/区(县)", trigger: "change"}],
            detailAddress: [{required: true, message: "请输入详细地址", trigger: "blur"}],
            postCode: [
              {required: true, message: "请输入邮编", trigger: "blur"},
              {pattern: this.pattern.postCode, message: "邮编格式不正确", trigger: "blur"}
            ]
          }
        },
        formColumns:[
          {
            label: "省/市/区（县）",
            prop: "province",
            template: true
          },
          {
            label: "详细地址",
            prop: "detailAddress",
            comp:{
              compType: 'input',
              attrs:{
                type: 'textarea',
                maxlength: 50,
                showWordLimit: true,
                autosize: {
                  minRows: 3
                }
              }
            }
          },
          {
            label: "邮编",
            prop: "postCode",
            comp:{
              compType: 'input',
              attrs:{
                maxlength: 6,
                showWordLimit: true
              }
            }
          },
          {
            label: "排序",
            prop: "sort",
            comp:{
              compType: 'input-number',
              attrs:{
                stepStrictly: true
              }
            }
          }
        ],
      }
    }
  },
  created(){ this.loadData() },
  methods:{
    loadData(){
      this.$yAxios({
        url: this.$api.self.pickupAddressList,
        data: {},
        loading: true,
      }, info => {
        this.tableData = info;
      })
    },
    resetForm(data = this.forms.currentForm){
      this.forms.formModel = Object.assign({
        id: '',
        province: '',
        city: '',
        region: '',
        detailAddress: '',
        postCode: '',
        sort: ''
      }, data || {})
    },
    addAddress(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editAddress(data){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = data;
      this.resetForm();
      this.forms.showForm = true;
    },
    delAddress(data){
      this.$yAxios({
        url: this.$api.self.delPickupAddress,
        data:{
          ids: [data.id]
        },
        loading: true
      }, info => {
        this.loadData();
      })
    },
    ensureModel(form){
      let newForm, url = this.$api.self.savePickupAddress;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({}, form);
      }
      this.$yAxios({
        url,
        data: newForm,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.loadData();
      })
    }
  }
}
</script>

<style scoped lang="less">
.pickupAddress{
  margin-top: -20px;
}
</style>